package com.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.api.gateway.demo.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import static com.file.APPCodeDemo.getParam;
import static org.springframework.util.ResourceUtils.getFile;
import static sun.plugin2.util.SystemUtil.decodeBase64;

/**
 * @author : gelianbin
 * @createDate : 2021/4/15
 */
public class MainTest2 {

    // 图片文件夹路径
    private static final String BASE_IMG_PATH = "G:\\screenshots";
    // 输出路径
    private static final String saveExcel = "G:\\screenshots\\"; //图片名称
    // 输出文件格式
    private static final String TXT_POSTFIX = ".txt";

    public static void main(String[] args) throws Exception {

        // 获取所有图片文件
        File dir = getFile(BASE_IMG_PATH);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            throw new FileNotFoundException();
        }

        // 获取每个图片的base64值，存入map
        Map<String, String> imgBase64 = new HashMap<>();
        int i = 0;
        for (File img : files) {
            i++;
            byte[] imgData = ImageToBaseUtil.getFileBytes(img);
            String base64 = ImageToBaseUtil.getImgBase64(imgData);

            String[] strings = img.getName().split("\\.");
            String fileName = strings[0]+strings[1];
            imgBase64.put(fileName, base64);
            System.out.println(fileName + base64);

            String host = "https://form.market.alicloudapi.com";
            String path = "/api/predict/ocr_table_parse";
            String appcode = "fad5749ecd8c4cd390a6e8164ed73a85";
            Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
            //请根据线上文档修改configure字段
            JSONObject configObj = new JSONObject();
            configObj.put("format", "xlsx");
            configObj.put("finance", false);
            configObj.put("dir_assure", false);
            String config_str = configObj.toString();
            //            configObj.put("min_size", 5);
            //String config_str = "";

            String method = "POST";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);

            Map<String, String> querys = new HashMap<String, String>();

            // 拼装请求body的json字符串
            JSONObject requestObj = new JSONObject();
            try {
                if (is_old_format) {
                    JSONObject obj = new JSONObject();
//                    obj.put("image", getParam(50, imgBase64));
                    obj.put("image", getParam(50, base64));

                    if (config_str.length() > 0) {
                        obj.put("configure", getParam(50, config_str));
                    }
                    JSONArray inputArray = new JSONArray();
                    inputArray.add(obj);
                    requestObj.put("inputs", inputArray);
                } else {
//                    requestObj.put("image", imgBase64);
                    requestObj.put("image", base64);
                    if (config_str.length() > 0) {
                        requestObj.put("configure", config_str);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String bodys = requestObj.toString();

            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if (stat != 200) {
                    System.out.println("Http code: " + stat);
                    System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                    System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                    return;
                }

                String res = EntityUtils.toString(response.getEntity());
                JSONObject res_obj = JSON.parseObject(res);
                if (is_old_format) {
                    JSONArray outputArray = res_obj.getJSONArray("outputs");
                    String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                    JSONObject out = JSON.parseObject(output);
                    System.out.println(out.toJSONString());
                } else {
                    System.out.println(res_obj.toJSONString());
                }
               //将结果写入excel
                if (res_obj.containsKey("success") && res_obj.getBoolean("success")) {
                    long timeMillis = System.currentTimeMillis();
//                    String saveFile = saveExcel + String.valueOf(timeMillis) + ".xlsx";
                    String saveFile = saveExcel +fileName + ".xlsx";
                    File file = new File(saveFile);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    FileOutputStream out = new FileOutputStream(file);
                    byte excel[] = decodeBase64(res_obj.getString("tables").replace("\\n", ""));
                    out.write(excel);
                    out.flush();
                    out.close();
                    System.out.println(file.getName());
                }
        } catch (Exception e) {
            e.printStackTrace();
        }

        }
    }
}


